#include "user_tcp_auth.h"
#include "user_crc.h"

#include <time.h>
#include <stdlib.h>
#include <string.h>

#define USER_TCP_AUTH_GET_KEY_HEAD  (0x5a5e1171)

#define HARDWARE_VERSION_SUB2		        0       ///< 0-不带继电器，1-带继电器

static char g_station_mac[6] = {0x01,0x02, 0x03,0x01,0x02, 0x03};

void swap(unsigned char *a, unsigned char* b)
{
    if(*a == *b)
        return;

    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}
/**
 * 将len位数据向前移动一位 
 */
void move(unsigned char *buf, int len)
{
    int i = 0;
    unsigned char tmp = buf[0];
    for(; i < len; i++)
    {
        buf[i] = buf[i + 1];
    }
    buf[i] = tmp;
}

uint32_t user_tools_get_tstamp_s(void)
{
    time_t t;
    t=time(0);
    return t;
}

int user_tcp_get_data(void* _des, const void* _res, int _cnt)
{
    memcpy(_des, _res, _cnt);
	return _cnt;
}



int user_tcp_auth_msg_get_time(uint8_t* dout)
{
    unsigned char buf[12] = {0};
    int send_len = 0;
    unsigned short crc = 0;
    const unsigned int msg1_head = 0x11223344;
    send_len += user_tcp_get_data(buf + send_len, &msg1_head, sizeof(msg1_head));
    send_len += user_tcp_get_data(buf + send_len, g_station_mac, sizeof(g_station_mac));
    crc = crc_cal(buf, send_len + 2);
    send_len += user_tcp_get_data(buf + send_len, &crc, sizeof(crc));
    
    memcpy((char *)dout, buf, send_len);
    return send_len;
}

int user_tcp_auth_get(uint8_t* dout)
{
    int send_len = 0;
    int r1, r2;
    unsigned int time_stamp;
    unsigned short crc;
    unsigned char buf[24] = {0};
    // test xbb
    const unsigned int g_magic_word = USER_TCP_AUTH_GET_KEY_HEAD + (HARDWARE_VERSION_SUB2 << 24);
    // const unsigned int g_magic_word = USER_TCP_AUTH_GET_KEY_HEAD + (HARDWARE_VERSION_DEVICE << 24);

    time_stamp = user_tools_get_tstamp_s();
    r1 = rand();
    r2 = rand();
    send_len += user_tcp_get_data(buf + send_len, &g_magic_word, sizeof(g_magic_word));
    send_len += user_tcp_get_data(buf + send_len, g_station_mac, 6);
    send_len += user_tcp_get_data(buf + send_len, &r1, sizeof(r1));
    send_len += user_tcp_get_data(buf + send_len, &time_stamp, sizeof(time_stamp));
    send_len += user_tcp_get_data(buf + send_len, &r2, sizeof(r2));
    
    //mac偶数,time byte0<->byte2
    //mac奇数,time byte1<->byte3
    swap(&buf[14 + (buf[9] & 0x01)], &buf[16 + (buf[9] & 0x01)]);
    move(&buf[13], sizeof(time_stamp));
    crc = crc_cal(buf, send_len + 2);
    send_len += user_tcp_get_data(buf + send_len, &crc, sizeof(crc));

    memcpy((char *)dout, buf, send_len);
    return send_len;
}